package cn.javase.concurrent._并发编程._04_共享模型之管程._synchronized;

import java.util.Random;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

@Slf4j
public class _转账练习 {

    // 账户
    class Account {
        private int money;
        public Account(int money) {
            this.money = money;
        }
        public int getMoney() {
            return money;
        }
        public void setMoney(int money) {
            this.money = money;
        }
        public void transfer(Account target, int amount) {
            synchronized (Account.class) {
                if (this.money > amount) {
                    this.setMoney(this.getMoney() - amount);
                    target.setMoney(target.getMoney() + amount);
                }
            }
        }
    }

    // Random 为线程安全
    static Random random = new Random();
    // 随机 1~100
    public static int randomAmount() {
        return random.nextInt(100) +1;
    }

    // a和b两个账户相互进行转账
    @Test
    public void test() throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        // 查看转账2000次后的总金额
        log.debug("a: {}", a.getMoney());
        log.debug("b: {}", b.getMoney());
        log.debug("total: {}",(a.getMoney() + b.getMoney()));
    }

}
